import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import ApiResult from "@/model/ApiResult";
// 自定义请求返回数据的类型

class HRequest {
  config: AxiosRequestConfig;

  instance: AxiosInstance;

  constructor() {
    this.config = {
      headers: {
        token: window.sessionStorage.getItem('token')
      }
    };

    this.instance = axios.create(this.config);
  }

  // 类型参数的作用，T决定AxiosResponse实例中data的类型
  request<T = any>(config: AxiosRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      this.instance
        .request<any, ApiResult<T>>(config)
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  get<T = any>(url: string, params: any): Promise<T> {
    return this.request({
      url,
      params,
      method: 'GET'
    });
  }

  post<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'POST' });
  }

  postForm<T = any>(url: string, data: any): Promise<T> {
    return this.request({
      url,
      data,
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    });
  }

  async postFormSync<T = any>(url: string, data: any): any{
    return await this.instance
      .request<any, ApiResult<T>>({
        url,
        data,
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      })
  }
  delete<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'DELETE' });
  }

  patch<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request({
      ...config,
      method: 'PATCH'
    });
  }
}

export default new HRequest()
